﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using AutoUpdateClient;
using AutoUpdateClient.WebReference;
using ZhCun.Framework.Common;

namespace AccountManager.AppUpdate
{
    public partial class FrmAppUpdate : BaseForm
    {
        private FrmAppUpdate()
        {
            InitializeComponent();
        }
        static FrmAppUpdate _instance;

        public static FrmAppUpdate Create()
        {
            if (_instance == null || _instance.IsDisposed)
            {
                _instance = new FrmAppUpdate();
            }
            return _instance;
        }

        static void WriteUpdateLogs(string content)
        {
            LogHelper.WriteLog("UpdateLogs", content);
        }

        static UpdateHelper _UpdateObj;

        public static bool IsNeedUpdate()
        {
            try
            {
                if (_UpdateObj == null)
                {
                    _UpdateObj = new UpdateHelper();
                }
                //如果已经创建实例,或已打开,就不再判断,因为执行GetCanUpdateFile 会改变全局文件信息变量
                if (_instance != null && _instance.IsDisposed)
                {
                    return false;
                }
                FileInfoModel[] fileModels = _UpdateObj.GetCanUpdateFile();
                return fileModels.Length > 0 ? true : false;
            }
            catch (Exception ex)
            {
                WriteUpdateLogs("初始化更新对象失败,或没连接到服务器!" + ex.Message);
                return false;
            }
        }
        /// <summary>
        /// 窗体启动时是否开始更新
        /// </summary>
        public bool IsAutoStart = false;

        /// <summary>
        /// 写当前运行状态到控件
        /// </summary>
        void WriteState(string msg, params object[] args)
        {
            string msgText = string.Format(msg, args);
            lboxDetail.Text = msgText;
            lboxDetail.Items.Insert(0, msgText + "[ " + DateTime.Now.ToString("HH:mm:ss") + " ] ");
        }

        private void FrmAppUpdate_Load(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(a =>
            {
                if (_UpdateObj == null)
                {
                    _UpdateObj = new UpdateHelper();                    
                }
                _UpdateObj.DownloadFileBeforeHandle += UpdateObj_DownloadFileBeforeHandle;
                _UpdateObj.DownloadFileCountHandle += UpdateObj_DownloadFileCountHandle;
                _UpdateObj.DownloadFileAfterHandle += UpdateObj_DownloadFileAfterHandle;
                _UpdateObj.DownloadOverHandle += UpdateObj_DownloadOverHandle;
                _UpdateObj.DownloadErrorHandle += UpdateObj_DownloadErrorHandle;
                if (IsAutoStart)
                {
                    btnStartUpdate_Click(sender, e);
                }
            }));
        }

        private void btnStartUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                btnStartUpdate.Enabled = false;
                FileInfoModel[] fileModels = _UpdateObj.GetCanUpdateFile();
                WriteState("总共需要更新文件{0}个", fileModels.Length);
                int downCount = _UpdateObj.StartUpdate();
                if (downCount == 0)
                {
                    WriteState("没有要更新的文件");
                }
                progressBar.Maximum = downCount;
            }
            catch (Exception ex)
            {
                btnStartUpdate.Enabled = true;
                MessageBox.Show("下载数据时出错,原因:" + ex.Message);
            }
        }

        void UpdateObj_DownloadFileBeforeHandle(UpdateHelper upObj, FileInfoModel fileModel)
        {
            WriteState("正在下载文件{0}", fileModel.FileName);
        }
        void UpdateObj_DownloadFileCountHandle(UpdateHelper upObj, FileInfoModel fileModel)
        {
            if (progressBar.Value < progressBar.Maximum)
                progressBar.Value++;
        }
        void UpdateObj_DownloadFileAfterHandle(UpdateHelper upObj, FileInfoModel fileModel)
        {
            WriteState("下载文件{0}完成", fileModel.FileName);
        }
        void UpdateObj_DownloadOverHandle(UpdateHelper upObj, FileInfoModel fileModel)
        {
            WriteState("文件全部下载完成,请重新启动软件");
        }
        void UpdateObj_DownloadErrorHandle(UpdateHelper upObj, FileInfoModel fileModel)
        {
            WriteState("下载文件{0}异常,原因:{1}", fileModel.FileName, upObj.DownloadException.Message);
        }
    }
}